// miniprogram/pages/admin/productList/list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: {},
    listData: [],
    dialogShow: false,
    buttons: [{text: '取消'}, {text: '确定'}],
    attrList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
  },
  /**
   * 初始化数据 
   */
  initData: function () {
    const that = this;
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'productapi',
      // 传给云函数的参数
      data: {
        method: "queryProductPage",
        args: {pageNo:1, pageSize:20, isAdmin: true}
      },
      // 成功回调
      complete: (res)=>{
        console.log(res, "产品列表")
        that.setData({
          page: res.result.rstData,
          listData: res.result.rstData.data
        });
      }
    })
  },
  // 修改商品状态
  updateStatus(e) {
    console.log(e,"下架");
    const _id = e.currentTarget.dataset.id;
    const status = e.currentTarget.dataset.status;
    let param = {
      status: status,
      _id: _id
    };
    console.log("参数", param);
    this.updateApi(param);
  },
  // 修改库存
  updateStk(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
        dialogShow: true,
        attrList: item.attr,
        _id: item._id
    });
  },
  updateApi(param) {
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'productapi',
      // 传给云函数的参数
      data: {
        method: "save",
        args: param
      },
      // 成功回调
      success: (res)=>{
        console.log(res, "修改");
        this.initData();
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        });
      }
    })
  },
  tapDialogButton(e) {
    console.log("确认修改库存", e);
    let data = {
      _id: this.data._id
    };
    if(e.detail.item.text === "确定") {
      let num = 0;
      const attr = this.data.attrList.map(item=> {
        item.attrStk = Number(item.attrStk);
        num = num + item.attrStk;
        return item;
      });
      data.attr = attr;
      data.sumStk = num;
      this.updateApi(data);
      this.setData({dialogShow: false});
      console.log(data,"数据");
    }else {
      this.setData({dialogShow: false});
      console.log(data,"数据");
    }
  },
  /**属性与库存输入处理函数 */
  attrInputHander(e) {
      console.log("库存数处理", e)
      const index = e.currentTarget.dataset.index;
      const field = e.currentTarget.dataset.field;
      this.data.attrList[index][field] = e.detail.value;
      console.log(this.data.attrList)
  },
})